<?php
/**
 * 栏目管理模型
 * 
 + ----------------------------------------------------- 
 * Date 2013-3-8
 + -----------------------------------------------------
 */
class MenuModel extends CommonModel {
	
	protected $_validate	=	array(
		array('menu_name','require','请输入栏目名称！'),
	);

	protected $_auto		=	array(
		array('add_time','time',1,'function'),
		array('path','getPath',3,'callback'),
	);
	
	protected function getPath(){
		$path=0;
		if(isset($_POST['parent_id'])){
			$Ppath=$this->where("id=".$_POST['parent_id'])->getField("path");
			if(isset($Ppath)){
				$path=$Ppath.'-'.$_POST['parent_id'];
			}
		}
		return $path;
	}
	
	/**
      +----------------------------------------------------------
     * 所有子栏目
	 * @param pid  父级ID
	  +----------------------------------------------------------
     */
	public function getSubmenuList($pid=0,$limit=5){
		$map['m.parent_id']=$pid;
		$menus=$this->table(C("DB_PREFIX")."menu m")
			->join("left join ".C("DB_PREFIX")."menu_type t on m.type_id=t.id")
			->field("m.*,t.name,t.model")
			->where($map)
			->order("m.sort_order asc,m.id asc")
			->limit($limit)
			->select();
		return $menus;
	}
	
	/**
      +----------------------------------------------------------
     * 所有子栏目id
	 * @param pid  父级ID
	  +----------------------------------------------------------
     */
	public function getSubmenuId($pid=0){
		$ids=array();
		$pids[]=$pid;
		$map['parent_id']=$pid;
		$menus=$this->where($map)->select();
		if(is_array($menus)&&count($menus)>0){
			foreach($menus as $k=>$v){
				$ids[]=$v['id'];
				$map['parent_id']=$v['id'];
				if($this->where($map)->count()>0){
					$ids=array_merge($ids,$this->getSubmenuId($v['id']));
				}
			}
		}
		return array_merge($ids,$pids);
	}
	
	/**
      +----------------------------------------------------------
     * 递归所有子栏目信息
	 * @param pid  父级ID
	  +----------------------------------------------------------
     */
	public function getSubmenu($pid=0,$select=0){
		$sub_menu=array();
		$map['link_id']=0;
		if(is_array($pid)){
			$map['id']=array('in',$pid);
		}else{
			$map['parent_id']=intval($pid);
		}
		$menus=$this->where($map)->select();
		if(is_array($menus)&&count($menus)>0){
			foreach($menus as $k=>$v){
				$seek='';
				if(empty($v['path'])){
					$seek='|-';
					$style='font-weight:bold;';
				}else{
					$array=@explode('-',$v['path']);
					$count=count($array)-1;
					for($i=0;$i<=$count;$i++){
						$seek.='|-';
					}
					$style='';
				}
				if($select==$v['id']){
					$select_html='selected="selected"';
				}else{
					$select_html='';
				}
				$sub_menu[]='<option '.$select_html.' value="'.$v['id'].'" style="'.$style.'">'.$seek.$v['menu_name'].'</option>';
				$map['parent_id']=$v['id'];
				$map['id']=array('gt',0);
				if($this->where($map)->count()>0){
					$sub_menu[]=$this->getSubmenu($v['id'],$select);
				}
			}
		}
		return implode('',$sub_menu);
	}
}
?>